package com.sunyard.domee.common.exception;

import com.sunyard.domee.common.model.ResultModel;
import com.sunyard.domee.commons.constants.CoreConstants;
import com.sunyard.domee.commons.constants.ErrorCode;
import com.sunyard.domee.commons.exception.AuthException;
import com.sunyard.domee.commons.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @program domee
 * @description
 * @author raoinyx@163.com
 * @create 2020-07-18 00:23
 */
@ControllerAdvice
@Slf4j
public class BusinessExceptionHandler {
    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public ResultModel messageExceptionHandler(RuntimeException ex) {
        log.info("统一异常处理：{}", CoreConstants.GSON.toJson(ex));
        ResultModel result = new ResultModel();
        if (ex instanceof AuthException) {
            AuthException authException = (AuthException) ex;
            result.setCode(authException.getErrorCode().getCode());
            result.setMessage(authException.getMessage());
            return result;
        }
        if (ex instanceof BusinessException) {
            BusinessException businessException = (BusinessException) ex;
            result.setCode(businessException.getErrorCode().getCode());
            result.setMessage(businessException.getMessage());
            return result;
        }
        result.setCode(ErrorCode.UNKNOW_ERROR.getCode());
        result.setMessage(ErrorCode.UNKNOW_ERROR.getMessage());
        result.setData("FAILED");
        log.info("统一异常处理返回：{}", CoreConstants.GSON.toJson(result));
        return result;
    }
}
